package com.javasm.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @version 0.1
 * @className: BaseServlet
 * @description:
 * @author: gfs
 * @date: 2025/6/23 11:06
 * @since: jdk17
 */
public class BaseServlet extends HttpServlet {

    /*
    * 1合并servlet
    *  自定义方法 通过service方法做请求分发
    * 2根据http协议规范 做请求分发 rest风格
    *  get     做查询
    *  put     做添加
    *  post    做修改
    *  delete  删除
    * 3 通过请求地址 menu/listSelect  结合service做请求分发
    *  /menus/* 通过url对应不同的方法
    *  通过反射 直接调用url中对应的方法对象
        //                      找类型对象        找到对象中的方法对象 方法名     参数类型
        Method declaredMethod = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
        //如果其他访问修饰符 需要设置方法穿透
        declaredMethod.setAccessible(true);
        //调用方法对象的方法  invoke执行方法对象 需要实例对象和实参
        declaredMethod.invoke(this,req,resp);

    *
    * */


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("统一重写service");
        String requestURI = req.getRequestURI();
        try {
            String methodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
            Method declaredMethod = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            declaredMethod.setAccessible(true);
            declaredMethod.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            resp.sendError(404);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
